package mongodb

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var client *mongo.Client

func NewMongoDB(ctx context.Context, appUri string) error {
	//连接到mongodb
	c, err := mongo.Connect(ctx, options.Client().ApplyURI(appUri))
	if err != nil {
		return err
	}
	//检查连接
	err = c.Ping(ctx, nil)
	if err != nil {
		return err
	}
	client = c
	log.Println("mongodb连接成功")
	return nil
}

type MongoDB struct {
	database   string
	collection string
}

func NewMGDB(database string, collection string) *MongoDB {
	if client == nil {
		log.Fatalln("mongo.Client Not initialized !")
	}
	return &MongoDB{
		database,
		collection,
	}
}

//新增一条记录
func (mg *MongoDB) InsertOne(ctx context.Context, value Sb_sbb_zb) *mongo.InsertOneResult {
	result, err := mg.getCollection().InsertOne(ctx, value)
	if err != nil {
		panic(err)
	}
	return result
}

func (mg *MongoDB) InsertDataMultiple(ctx context.Context, data []BigData) *mongo.InsertManyResult {
	var array []interface{}
	for i := 0; i < len(data); i++ {
		array = append(array, data[i])
	}
	result, err := mg.getCollection().InsertMany(ctx, array)
	if err != nil {
		panic(err)
	}
	return result
}

//新增多条记录
func (mg *MongoDB) InsertMultiple(ctx context.Context, data []Sb_sbb_zb) *mongo.InsertManyResult {
	var array []interface{}
	for i := 0; i < len(data); i++ {
		array = append(array, data[i])
	}
	result, err := mg.getCollection().InsertMany(ctx, array)
	if err != nil {
		panic(err)
	}
	return result
}

//新增多条记录
func (mg *MongoDB) InsertMultiple1(ctx context.Context, data []Sb_sbb_fb) *mongo.InsertManyResult {
	var array []interface{}
	for i := 0; i < len(data); i++ {
		array = append(array, data[i])
	}
	result, err := mg.getCollection().InsertMany(ctx, array)
	if err != nil {
		panic(err)
	}
	return result
}

//新增多条记录
func (mg *MongoDB) InsertMultiple2(ctx context.Context, data []Sb_sbjz_flb) *mongo.InsertManyResult {
	var array []interface{}
	for i := 0; i < len(data); i++ {
		array = append(array, data[i])
	}
	result, err := mg.getCollection().InsertMany(ctx, array)
	if err != nil {
		panic(err)
	}
	return result
}

//新增多条记录
func (mg *MongoDB) InsertMultiple3(ctx context.Context, data []Sb_sbjz_mxb) *mongo.InsertManyResult {
	var array []interface{}
	for i := 0; i < len(data); i++ {
		array = append(array, data[i])
	}
	result, err := mg.getCollection().InsertMany(ctx, array)
	if err != nil {
		panic(err)
	}
	return result
}

//获取表
func (mg *MongoDB) getCollection() *mongo.Collection {
	return client.Database(mg.database).Collection(mg.collection)
}

//定义过滤器
type filter bson.D

//创建一个条件查询对象
func Newfilter() filter {
	return filter{}
}
